import axios from "axios";
import { ElMessage, ElMessageBox ,ElLoading} from "element-plus";
import router from "../router/index";

const defBase = import.meta.env
axios.defaults.baseURL = defBase.VITE_URL_finace
const http = axios.create({
  headers: {
    // "Content-Type": "application/json",
    "platform": "plat"
    // 可以添加其他全局请求头
  },
  timeout:12000
});

// 请求拦截器
http.interceptors.request.use(
  (config) => {
    // 添加认证 token
    const token = localStorage.getItem("token");
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    // 请求错误处理
    ElMessage.error("请求错误: " + error.message);
    return Promise.reject(error);
  }
);

// 响应拦截器
http.interceptors.response.use(
  
  (response) => {

    if (response.data.code == 2000000) {
      if (document.getElementsByClassName("el-message").length > 0) return;
      ElMessage({
        type: "error",
        message: response.data.message,
      });
      ElMessageBox.confirm("请重新登录", response.data.message, {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          router.push("/login");
          return;
        })
        .catch(() => {
          ElMessage({
            type: "info",
            message: "token已失效,请重新登录",
          });
        });
      // router.replace({
      //   path:'/login'
      // })
    } else if (response.data.code == 1000000) {
      ElMessage({
        type: "error",
        message: response.data.message,
      });
    } else if (response.data.code == 1000001) {
      ElMessage({
        type: "error",
        message: response.data.message,
      });
    } else if (response.data.code == 1000002) {
      ElMessage({
        type: "error",
        message: response.data.message,
      });
    } else if (response.data.code == 1000003) {
      ElMessage({
        type: "error",
        message: response.data.message,
      });
    } else if (response.data.code == 1000004) {
      ElMessage({
        type: "error",
        message: response.data.message,
      });
    } else if (response.data.code == 1000005) {
      ElMessage({
        type: "error",
        message: response.data.message,
      });
    } else if (response.data.code == 1000010) {
      ElMessage({
        type: "error",
        message: response.data.message,
      });
    } else if (response.data.code == -1) {
      ElMessage({
        type: "error",
        message: response.data.message,
      });
    }
    // 处理200状态的响应

    if (response.status === 200) {
      return response.data;
    } else {
      throw new Error(response.data.message || "服务器错误");
    }
  },
  (error) => {
    // 响应错误处理
    if (error.response) {
      // 处理来自服务器的错误
      ElMessage.error("服务器错误: " + error.response.data.message);
    } else {
      // 处理其他错误（例如网络问题）
      ElMessage.error("网络开小差了，请联系客服");
    }
    return Promise.reject(error);
  }
);


export default http;
